
"""
Google Classroom backend

This file is part of polyglot, etc.
"""

import datetime
import random
import json
import re
from .support import Backend, Course, ResourceCategory, ResourceRawHTML, Task, FileUpload

from ..authentication import google as GoogleAuth
import pprint

class ClassroomCourse(Course):
    def __init__(self, data):
        # Course ID unique within this backend but not necessarily in general
        self.id = data["id"]

        # Course name and teacher name, no localisation?
        self.title = data["title"]
        self.teacher = data["teacher"]
        self.grade_summary = None

    @property
    def tasks(self):
        t = Task("Homework 2", datetime.datetime.now() + datetime.timedelta(days=1))
        t.resources = [ResourceRawHTML("Details", "Poke poke!")]
        return [t]

    def upload_file(self, id, file):
        return True

class ClassroomBackend(Backend):
    Config = ["Email", "Password"]

    def login(self, config):
        out = GoogleAuth.auth(self.session, config, "https://classroom.google.com/")
        p = out.text
        self.token = self.make_token(p)

        return True

    def fast_login(self, config):
        p = self.session.get("https://classroom.google.com/")
        self.token = self.make_token(p.text)

    def make_token(self, q):
        t = re.search("//drive.google.com/picker\\\\\",null,null,null,null,null,null,null,\\\\\"([^\\\\]*)\\\\\",null,null,", q, re.MULTILINE).group(1)
        return t

    def json_req(self, endpoint, req):
        q = self.session.post(endpoint + "?_reqid=" + str(random.randint(11111, 99999)) + "&rt=j", {
            "f.req": req,
            "token": self.token
        })

        # Split off anti-JSON hijacking junk

        return json.loads(q.text.split("\n", 1)[1].strip())
 
    @property
    def courses(self):
        #uq = "[[null,null,1],[true,true,[null,true,null,true,true,true,null,true,null,true],true,true,true,null,true,true,true,true,true,true,true,true],[[null,[[true]],[]],[]]]"
        #pprint.pprint(self.json_req("https://classroom.google.com/v6/queryuser", uq))

        uq = "[[100,null,1],[true,true,null,null,true,true,true,true,[null,true,true,true,null,true,[true],null,[true],true,true],true,true,null,true,true,true,null,true,true,null,null,[true,true],true,true,true,true,null,null,false,[true,true],true,true,true,true,true,true,true,true],[[null,[[true]],[]],[],[2],[1,2],true,[]]]"
        course_resp = self.json_req("https://classroom.google.com/v6/querycourse", uq)

        courses = []

        for course in course_resp[0][0][2]:
            c_id = course[0][0]
            title = course[5]
            time = course[8]
            instructor_id = course[6][0][0]

            courses += [ClassroomCourse({
                "id": c_id,
                "title": title,
                "time": time,
                "teacher": instructor_id
            })]

        return courses
